package leetcode_201_300;

import java.util.Arrays;

public class LeeCode_238 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(productExceptSelf(new int[]{-1, -1, 0, 1, 1})));
    }
    private static int[] productExceptSelf(int[] nums) {
        long[] ms = new long[nums.length + 1];
        ms[0] = 1;
        for (int i = 0; i < nums.length; i++) {
            ms[i + 1] = ms[i] * nums[i];
            if (nums[i] == 0){
                break;
            }
        }
        int[] ans = new int[nums.length];
        for (int i = 0; i < ans.length; i++) {
            if (nums[i] == 0){
                ans[i] = (int) ms[i];
                for (int j = i + 1; j < nums.length; j++) {
                    ans[i] *= nums[j];
                }
                for (int j = i + 1; j < ans.length; j++) {
                    ans[j] = 0;
                }
                break;
            }
            ans[i] = (int) (ms[i + 1] / nums[i] * (ms[ms.length - 1] / ms[i + 1]));
        }
        return ans;
    }
}
